package org.zjx.app.service;

import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;
import org.zjx.app.action.gather.GatherPropAction;
import org.zjx.command.state.AccountState;
import org.zjx.command.state.ItemState;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PropServiceAction extends Action {
    private static final String filePath = "item_state.json";

    public PropServiceAction(IWindow targetWindow) {
        super(targetWindow, true);
    }

    @Override
    protected void doExecute() throws Exception {
        ItemState itemState = stateManager.getState(ItemState.class);
        AccountState accountState = stateManager.getState(AccountState.class);
        String playerFilePath =  accountState.getPlayerId() + "-"+filePath;
        if (itemState == null) {
            itemState = getFilePath(new File(playerFilePath));
            if (itemState == null) {
                targetWindow.submitAction(new GatherPropAction(targetWindow));
                return;
            }
        }
        saveData(playerFilePath,itemState);
        stateManager.registerState(itemState);
        stateManager.getGameState().setGatherProp(true);
    }

    @SneakyThrows
    public void saveData(String playerFilePath,ItemState itemState) {
        String json = JSON.toJSONString(itemState);
        Files.write(Paths.get(playerFilePath), json.getBytes(StandardCharsets.UTF_8));
    }

    @SneakyThrows
    public ItemState getFilePath(File file) {
        if (!file.exists()) return null;
        String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        if (json.isEmpty()) return null;
        return JSON.parseObject(json, ItemState.class);
    }

}
